<?php
/**
 * 系统管理页面 V2 - 模态框编辑 + 实时保存
 * 解决复选框显示错误问题的全新交互方式
 */

// 错误报告设置
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);

// 开启会话
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// 检查用户是否已登录
if (!isset($_SESSION['user_id']) || !isset($_SESSION['username'])) {
    header('Location: index.php');
    exit();
}

// 为导航栏设置全局变量
$current_user_id = $_SESSION['user_id'] ?? '';
$GLOBALS['current_user_id'] = $current_user_id;

// 数据库连接
try {
    if (!file_exists('database.php')) {
        throw new Exception("database.php文件不存在");
    }

    require_once 'database.php';

    if (!isset($conn) || !($conn instanceof mysqli)) {
        throw new Exception("数据库连接失败");
    }

    if (!$conn->ping()) {
        throw new Exception("数据库连接已断开");
    }

} catch (Exception $e) {
    $_SESSION['error_message'] = "数据库连接失败：" . $e->getMessage();
    header('Location: user_home.php');
    exit();
}

// 初始化变量
$debug_info = [];
$success_message = '';
$error_message = '';
$all_roles = ['系统管理员', '考试项目管理员', '人事管理员', '普通账号'];
$high_level_roles = ['系统管理员', '考试项目管理员', '人事管理员'];

/**
 * 获取员工数据和角色信息
 */
function getStaffWithRoles($conn) {
    global $debug_info;
    $staff_with_roles = [];

    try {
        // 获取员工基本信息和角色信息的联合查询
        $sql = "
            SELECT
                s.user_id,
                s.name,
                s.serving,
                GROUP_CONCAT(ur.role ORDER BY ur.role SEPARATOR ',') as roles
            FROM staff s
            LEFT JOIN user_roles ur ON s.user_id = ur.user_id
            GROUP BY s.user_id, s.name, s.serving
            ORDER BY s.user_id
        ";

        $debug_info[] = "执行联合查询SQL: " . $sql;

        $result = $conn->query($sql);
        if (!$result) {
            $debug_info[] = "联合查询失败: " . $conn->error;
            return [];
        }

        $count = 0;
        while ($row = $result->fetch_assoc()) {
            $user_id = strval($row['user_id']);
            $roles = $row['roles'] ? explode(',', $row['roles']) : [];

            $staff_with_roles[$user_id] = [
                'user_id' => $user_id,
                'name' => $row['name'],
                'serving' => intval($row['serving']),
                'roles' => $roles,
                'high_level_roles' => array_intersect($roles, ['系统管理员', '考试项目管理员', '人事管理员']),
                'has_regular_role' => in_array('普通账号', $roles)
            ];
            $count++;
        }

        $debug_info[] = "成功获取 {$count} 条员工和角色记录";
        return $staff_with_roles;

    } catch (Exception $e) {
        $debug_info[] = "获取员工和角色数据时发生错误: " . $e->getMessage();
        return [];
    }
}

/**
 * 自动分配默认角色检测 - 借鉴system_management.php
 */
function autoAssignDefaultRoles($staff_with_roles) {
    global $debug_info;
    $updates_needed = [];

    $debug_info[] = "=== 自动同步检测开始（仅检测普通账号角色） ===";

    foreach ($staff_with_roles as $user_id => $staff) {
        $current_roles = $staff['roles'];
        $has_default_role = in_array('普通账号', $current_roles);
        $serving = intval($staff['serving']);

        // 只处理普通账号角色的同步检测
        if ($serving === 1 && !$has_default_role) {
            // 在职员工应该有普通账号角色
            $updates_needed[] = ['action' => 'add', 'user_id' => $user_id, 'role' => '普通账号', 'name' => $staff['name']];
            $debug_info[] = "需要添加: 用户{$user_id}({$staff['name']}) - 普通账号";
        } elseif ($serving === 0 && $has_default_role) {
            // 离职员工不应该有普通账号角色
            $updates_needed[] = ['action' => 'remove', 'user_id' => $user_id, 'role' => '普通账号', 'name' => $staff['name']];
            $debug_info[] = "需要移除: 用户{$user_id}({$staff['name']}) - 普通账号";
        }
    }

    $debug_info[] = "自动同步检测完成，需要处理 " . count($updates_needed) . " 条普通账号记录";
    $debug_info[] = "重要：高级角色（系统管理员、考试项目管理员、人事管理员）不受自动同步影响";

    return $updates_needed;
}

/**
 * 统计角色分配情况
 */
function calculateRoleStats($staff_with_roles) {
    $stats = [
        'total_staff' => count($staff_with_roles),
        'serving_staff' => 0,
        'retired_staff' => 0,
        'system_admin' => 0,
        'exam_admin' => 0,
        'hr_admin' => 0,
        'regular_users' => 0,
        'total_role_assignments' => 0
    ];

    foreach ($staff_with_roles as $staff) {
        if ($staff['serving']) {
            $stats['serving_staff']++;
        } else {
            $stats['retired_staff']++;
        }

        $roles = $staff['roles'];
        $stats['total_role_assignments'] += count($roles);

        if (in_array('系统管理员', $roles)) $stats['system_admin']++;
        if (in_array('考试项目管理员', $roles)) $stats['exam_admin']++;
        if (in_array('人事管理员', $roles)) $stats['hr_admin']++;
        if (in_array('普通账号', $roles)) $stats['regular_users']++;
    }

    return $stats;
}

// 获取数据
$debug_info[] = "=== 开始数据获取流程 ===";
$staff_with_roles = getStaffWithRoles($conn);
$role_stats = calculateRoleStats($staff_with_roles);
$auto_updates = autoAssignDefaultRoles($staff_with_roles);

$debug_info[] = "=== 数据获取完成 ===";
$debug_info[] = "员工总数: " . $role_stats['total_staff'];
$debug_info[] = "在职员工: " . $role_stats['serving_staff'];
$debug_info[] = "离职员工: " . $role_stats['retired_staff'];
$debug_info[] = "总角色分配: " . $role_stats['total_role_assignments'];
$debug_info[] = "系统管理员: " . $role_stats['system_admin'];
$debug_info[] = "考试项目管理员: " . $role_stats['exam_admin'];
$debug_info[] = "人事管理员: " . $role_stats['hr_admin'];
$debug_info[] = "普通账号: " . $role_stats['regular_users'];
$debug_info[] = "需要自动同步: " . count($auto_updates);

$page_title = '系统管理 V2 - 考务管理系统';
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($page_title); ?></title>

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <!-- 统一样式 -->
    <link rel="stylesheet" href="css/unified-style.css">

    <style>
    .main-content {
        margin-top: 20px;
        padding-bottom: 40px;
    }

    .page-header {
        text-align: center;
        padding: 30px 20px;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border-radius: 10px;
        margin-bottom: 30px;
    }

    .stats-cards {
        margin-bottom: 30px;
    }

    .stat-card {
        text-align: center;
        padding: 20px;
        border-radius: 8px;
        background: white;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }

    .stat-number {
        font-size: 2rem;
        font-weight: 700;
        margin-bottom: 5px;
    }

    .user-table th {
        background-color: #f8f9fa;
        text-align: center;
        padding: 12px 8px;
        position: sticky;
        top: 0;
        z-index: 10;
    }

    .user-table td {
        text-align: center;
        padding: 12px 8px;
        vertical-align: middle;
    }

    .user-info {
        text-align: left !important;
    }

    .user-id {
        font-weight: 600;
        color: #2c3e50;
        font-size: 14px;
    }

    .user-name {
        color: #6c757d;
        font-size: 13px;
    }

    .role-badges {
        display: flex;
        flex-wrap: wrap;
        gap: 4px;
        justify-content: center;
    }

    .role-badge {
        font-size: 11px;
        padding: 4px 8px;
    }

    .table-container {
        max-height: 600px;
        overflow-y: auto;
        border: 1px solid #dee2e6;
        border-radius: 8px;
    }

    .edit-btn {
        padding: 6px 12px;
        font-size: 12px;
    }

    .role-edit-modal .modal-body {
        padding: 30px;
    }

    .role-selection {
        margin: 20px 0;
    }

    .role-option {
        display: flex;
        align-items: center;
        padding: 12px;
        border: 2px solid #e9ecef;
        border-radius: 8px;
        margin-bottom: 10px;
        cursor: pointer;
        transition: all 0.3s ease;
    }

    .role-option:hover {
        border-color: #007bff;
        background-color: #f8f9ff;
    }

    .role-option.active {
        border-color: #007bff;
        background-color: #e7f3ff;
    }

    .role-option input[type="checkbox"] {
        margin-right: 12px;
        transform: scale(1.2);
    }

    .role-option .role-info {
        flex: 1;
    }

    .role-option .role-name {
        font-weight: 600;
        color: #2c3e50;
        margin-bottom: 4px;
    }

    .role-option .role-desc {
        font-size: 12px;
        color: #6c757d;
    }

    .toast-container {
        position: fixed;
        top: 20px;
        right: 20px;
        z-index: 9999;
    }

    .debug-section {
        background-color: #f8f9fa;
        border: 1px solid #dee2e6;
        border-radius: 8px;
        margin-top: 30px;
    }

    .debug-content {
        font-family: 'Courier New', monospace;
        font-size: 12px;
        max-height: 400px;
        overflow-y: auto;
        white-space: pre-wrap;
        background-color: #ffffff;
        padding: 15px;
        border-radius: 4px;
    }
    </style>
</head>
<body>
    <!-- 统一导航栏 -->
    <?php
    if (file_exists('common/navigation.php')) {
        include_once 'common/navigation.php';
    } else {
        // 备用导航栏
        echo '<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
                <div class="container">
                    <a class="navbar-brand" href="dashboard.php">考务管理系统</a>
                    <div class="navbar-nav ms-auto">
                        <span class="navbar-text me-3">用户: ' . htmlspecialchars($current_user_id) . '</span>
                        <a class="nav-link" href="logout.php">退出登录</a>
                    </div>
                </div>
              </nav>';
    }
    ?>

    <!-- Toast 容器 -->
    <div class="toast-container"></div>

    <!-- 主要内容 -->
    <div class="container main-content">
        <!-- 页面标题 -->
        <div class="page-header">
            <h1 class="page-title">
                <i class="fas fa-users-cog"></i> 系统管理 V2
            </h1>
            <p class="page-subtitle">全新的模态框编辑 + 实时保存交互方式</p>
        </div>

        <!-- 消息提示 -->
        <?php if (!empty($success_message)): ?>
            <div class="alert alert-success alert-dismissible fade show">
                <i class="fas fa-check-circle"></i> <?php echo htmlspecialchars($success_message); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <?php if (!empty($error_message)): ?>
            <div class="alert alert-danger alert-dismissible fade show">
                <i class="fas fa-exclamation-triangle"></i> <?php echo htmlspecialchars($error_message); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <!-- 功能说明 -->
        <div class="alert alert-info">
            <strong><i class="fas fa-lightbulb"></i> 全新交互方式：</strong>
            <ul class="mb-0 mt-2">
                <li><strong>模态框编辑</strong> - 点击"编辑角色"按钮，在弹窗中修改用户角色</li>
                <li><strong>实时保存</strong> - 选择角色后立即保存到数据库，无需表单提交</li>
                <li><strong>即时反馈</strong> - 操作结果立即显示，表格自动更新</li>
                <li><strong>错误隔离</strong> - 单个用户操作失败不影响其他用户</li>
                <li><strong>自动同步</strong> - 根据在职状态自动同步普通账号角色</li>
            </ul>
        </div>

        <!-- 统计信息 -->
        <div class="row stats-cards">
            <div class="col-md-3">
                <div class="stat-card">
                    <div class="stat-number text-primary"><?php echo $role_stats['total_staff']; ?></div>
                    <div class="stat-label">总员工数</div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stat-card">
                    <div class="stat-number text-info"><?php echo $role_stats['total_role_assignments']; ?></div>
                    <div class="stat-label">总角色分配</div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stat-card">
                    <div class="stat-number text-success"><?php echo $role_stats['system_admin'] + $role_stats['exam_admin'] + $role_stats['hr_admin']; ?></div>
                    <div class="stat-label">管理员角色</div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stat-card">
                    <div class="stat-number text-warning"><?php echo count($auto_updates); ?></div>
                    <div class="stat-label">需要同步</div>
                </div>
            </div>
        </div>

        <!-- 普通账户自动同步 -->
        <div class="card mb-4">
            <div class="card-header">
                <i class="fas fa-sync"></i> 普通账户自动同步
            </div>
            <div class="card-body">
                <p>根据员工在职状态自动同步普通账号角色：</p>
                <ul>
                    <li>在职员工自动获得普通账号角色</li>
                    <li>离职员工自动移除普通账号角色</li>
                    <li>不影响管理员角色（系统管理员、考试项目管理员、人事管理员）</li>
                </ul>

                <?php if (!empty($auto_updates)): ?>
                    <div class="alert alert-warning">
                        <strong>发现 <?php echo count($auto_updates); ?> 条需要同步的记录</strong>
                        <ul class="mb-0 mt-2">
                            <?php foreach (array_slice($auto_updates, 0, 5) as $update): ?>
                                <li>用户<?php echo $update['user_id']; ?>(<?php echo $update['name']; ?>): <?php echo $update['action'] === 'add' ? '添加' : '移除'; ?>普通账号角色</li>
                            <?php endforeach; ?>
                            <?php if (count($auto_updates) > 5): ?>
                                <li>...还有 <?php echo count($auto_updates) - 5; ?> 条记录</li>
                            <?php endif; ?>
                        </ul>
                    </div>

                    <button type="button" class="btn btn-success" onclick="performAutoSync()">
                        <i class="fas fa-sync"></i> 执行自动同步 (<?php echo count($auto_updates); ?>条)
                    </button>
                <?php else: ?>
                    <div class="alert alert-success">
                        <i class="fas fa-check"></i> 所有普通账号角色已同步，无需处理
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- 用户角色管理表格 -->
        <div class="card">
            <div class="card-header">
                <i class="fas fa-users-cog"></i> 用户角色管理
                <small class="text-muted ms-2">
                    显示 <?php echo $role_stats['total_staff']; ?> 条记录 | 角色分配: <?php echo $role_stats['total_role_assignments']; ?> 条
                </small>
            </div>
            <div class="card-body p-0">
                <?php if (empty($staff_with_roles)): ?>
                    <div class="alert alert-warning m-3">
                        <i class="fas fa-exclamation-triangle"></i>
                        没有找到员工数据
                    </div>
                <?php else: ?>
                    <div class="table-container">
                        <table class="table table-hover user-table mb-0" id="userTable">
                            <thead>
                                <tr>
                                    <th style="width: 200px;">用户信息</th>
                                    <th style="width: 120px;">在职状态</th>
                                    <th style="width: 300px;">当前角色</th>
                                    <th style="width: 150px;">操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($staff_with_roles as $user_id => $staff): ?>
                                    <tr id="user-row-<?php echo $user_id; ?>">
                                        <td class="user-info">
                                            <div class="user-id"><?php echo htmlspecialchars($user_id); ?></div>
                                            <div class="user-name"><?php echo htmlspecialchars($staff['name']); ?></div>
                                        </td>
                                        <td>
                                            <?php if ($staff['serving']): ?>
                                                <span class="badge bg-success">在职</span>
                                            <?php else: ?>
                                                <span class="badge bg-secondary">离职</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <div class="role-badges" id="role-badges-<?php echo $user_id; ?>">
                                                <?php if (empty($staff['roles'])): ?>
                                                    <span class="badge bg-light text-dark role-badge">无角色</span>
                                                <?php else: ?>
                                                    <?php foreach ($staff['roles'] as $role): ?>
                                                        <?php
                                                        $badge_class = 'bg-secondary';
                                                        if ($role === '系统管理员') $badge_class = 'bg-danger';
                                                        elseif ($role === '考试项目管理员') $badge_class = 'bg-primary';
                                                        elseif ($role === '人事管理员') $badge_class = 'bg-warning';
                                                        elseif ($role === '普通账号') $badge_class = 'bg-secondary';
                                                        ?>
                                                        <span class="badge <?php echo $badge_class; ?> role-badge"><?php echo htmlspecialchars($role); ?></span>
                                                    <?php endforeach; ?>
                                                <?php endif; ?>
                                            </div>
                                        </td>
                                        <td>
                                            <button class="btn btn-primary edit-btn" onclick="editUserRoles('<?php echo $user_id; ?>', '<?php echo htmlspecialchars($staff['name']); ?>')">
                                                <i class="fas fa-edit"></i> 编辑角色
                                            </button>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- 调试信息 -->
        <?php if (!empty($debug_info)): ?>
        <div class="debug-section">
            <div class="card-header">
                <i class="fas fa-bug"></i> 详细调试信息
                <button class="btn btn-sm btn-outline-secondary float-end" onclick="toggleDebug()">
                    <i class="fas fa-eye"></i> 显示/隐藏
                </button>
            </div>
            <div class="debug-content" id="debugContent" style="display: none;">
<?php echo implode("\n", $debug_info); ?>

=== 最终数据统计 ===
员工总数: <?php echo $role_stats['total_staff']; ?>
在职员工: <?php echo $role_stats['serving_staff']; ?>
离职员工: <?php echo $role_stats['retired_staff']; ?>
总角色分配数: <?php echo $role_stats['total_role_assignments']; ?>
系统管理员: <?php echo $role_stats['system_admin']; ?>
考试项目管理员: <?php echo $role_stats['exam_admin']; ?>
人事管理员: <?php echo $role_stats['hr_admin']; ?>
普通账号: <?php echo $role_stats['regular_users']; ?>
需要自动同步: <?php echo count($auto_updates); ?>

=== 新版本特性 ===
交互方式: 模态框编辑 + 实时保存
复选框问题: 已彻底解决
状态同步: 无需同步，实时从数据库获取
错误处理: 单用户操作，错误隔离
用户体验: 直观编辑，即时反馈
自动同步: 普通账号角色自动同步
AJAX修复: 已修复网络错误问题
            </div>
        </div>
        <?php endif; ?>
    </div>

    <!-- 角色编辑模态框 -->
    <div class="modal fade role-edit-modal" id="roleEditModal" tabindex="-1" aria-labelledby="roleEditModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="roleEditModalLabel">
                        <i class="fas fa-user-edit"></i> 编辑用户角色
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="user-info-display">
                        <h6>用户信息：<span id="editUserName"></span> (<span id="editUserId"></span>)</h6>
                    </div>

                    <div class="role-selection">
                        <h6>选择角色：</h6>

                        <div class="role-option" data-role="系统管理员">
                            <input type="checkbox" id="role-system-admin" value="系统管理员">
                            <div class="role-info">
                                <div class="role-name">
                                    <i class="fas fa-cog text-danger"></i> 系统管理员
                                </div>
                                <div class="role-desc">拥有系统最高权限，可以管理所有功能</div>
                            </div>
                        </div>

                        <div class="role-option" data-role="考试项目管理员">
                            <input type="checkbox" id="role-exam-admin" value="考试项目管理员">
                            <div class="role-info">
                                <div class="role-name">
                                    <i class="fas fa-clipboard-list text-primary"></i> 考试项目管理员
                                </div>
                                <div class="role-desc">管理考试项目、考试安排和相关业务</div>
                            </div>
                        </div>

                        <div class="role-option" data-role="人事管理员">
                            <input type="checkbox" id="role-hr-admin" value="人事管理员">
                            <div class="role-info">
                                <div class="role-name">
                                    <i class="fas fa-user-tie text-warning"></i> 人事管理员
                                </div>
                                <div class="role-desc">管理员工信息、角色分配和人事相关业务</div>
                            </div>
                        </div>

                        <div class="role-option" data-role="普通账号">
                            <input type="checkbox" id="role-regular" value="普通账号">
                            <div class="role-info">
                                <div class="role-name">
                                    <i class="fas fa-user text-secondary"></i> 普通账号
                                </div>
                                <div class="role-desc">基础用户权限，可以使用基本功能</div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        <i class="fas fa-times"></i> 取消
                    </button>
                    <button type="button" class="btn btn-success" id="saveRolesBtn" onclick="saveUserRoles()">
                        <i class="fas fa-save"></i> 保存角色
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>

    <script>
    let currentEditUserId = null;
    let currentEditUserName = null;
    let roleEditModal = null;

    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', function() {
        console.log('系统管理页面 V2 加载完成 - 模态框编辑 + 实时保存 + 自动同步');

        // 初始化模态框
        roleEditModal = new bootstrap.Modal(document.getElementById('roleEditModal'));

        // 绑定角色选项点击事件
        document.querySelectorAll('.role-option').forEach(option => {
            option.addEventListener('click', function(e) {
                if (e.target.type !== 'checkbox') {
                    const checkbox = this.querySelector('input[type="checkbox"]');
                    checkbox.checked = !checkbox.checked;
                }
                updateRoleOptionStyle(this);
            });
        });

        // 绑定复选框变化事件
        document.querySelectorAll('.role-option input[type="checkbox"]').forEach(checkbox => {
            checkbox.addEventListener('change', function() {
                updateRoleOptionStyle(this.closest('.role-option'));
            });
        });

        console.log('✅ 模态框编辑系统初始化完成');
    });

    // 更新角色选项样式
    function updateRoleOptionStyle(option) {
        const checkbox = option.querySelector('input[type="checkbox"]');
        if (checkbox.checked) {
            option.classList.add('active');
        } else {
            option.classList.remove('active');
        }
    }

    // 编辑用户角色
    function editUserRoles(userId, userName) {
        currentEditUserId = userId;
        currentEditUserName = userName;

        console.log('编辑用户角色:', userId, userName);

        // 设置模态框标题
        document.getElementById('editUserId').textContent = userId;
        document.getElementById('editUserName').textContent = userName;

        // 获取用户当前角色
        getCurrentUserRoles(userId);

        // 显示模态框
        roleEditModal.show();
    }

    // 获取用户当前角色
    function getCurrentUserRoles(userId) {
        fetch('ajax_role_management.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                action: 'get_roles',
                user_id: userId
            })
        })
        .then(response => {
            console.log('Response status:', response.status);
            if (!response.ok) {
                throw new Error(`HTTP错误: ${response.status}`);
            }
            return response.text();
        })
        .then(text => {
            console.log('Response text:', text);
            try {
                const data = JSON.parse(text);

                if (data.success) {
                    // 重置所有复选框
                    document.querySelectorAll('.role-option input[type="checkbox"]').forEach(checkbox => {
                        checkbox.checked = false;
                        updateRoleOptionStyle(checkbox.closest('.role-option'));
                    });

                    // 设置当前角色
                    data.roles.forEach(role => {
                        const checkbox = document.querySelector(`input[value="${role}"]`);
                        if (checkbox) {
                            checkbox.checked = true;
                            updateRoleOptionStyle(checkbox.closest('.role-option'));
                        }
                    });

                    console.log('✅ 用户角色加载完成:', data.roles);
                } else {
                    showToast('获取用户角色失败：' + data.error, 'error');
                }
            } catch (jsonError) {
                console.error('JSON解析错误:', jsonError);
                showToast('服务器响应格式错误', 'error');
            }
        })
        .catch(error => {
            console.error('获取用户角色失败:', error);
            showToast('网络错误：' + error.message, 'error');
        });
    }

    // 保存用户角色
    function saveUserRoles() {
        if (!currentEditUserId) {
            showToast('用户ID错误', 'error');
            return;
        }

        // 获取选中的角色
        const selectedRoles = [];
        document.querySelectorAll('.role-option input[type="checkbox"]:checked').forEach(checkbox => {
            selectedRoles.push(checkbox.value);
        });

        console.log('保存用户角色:', currentEditUserId, selectedRoles);

        // 禁用保存按钮
        const saveBtn = document.getElementById('saveRolesBtn');
        const originalText = saveBtn.innerHTML;
        saveBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 保存中...';
        saveBtn.disabled = true;

        // 发送请求
        fetch('ajax_role_management.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                action: 'save_roles',
                user_id: currentEditUserId,
                roles: selectedRoles
            })
        })
        .then(response => {
            console.log('Response status:', response.status);
            if (!response.ok) {
                throw new Error(`HTTP错误: ${response.status}`);
            }
            return response.text();
        })
        .then(text => {
            console.log('Response text:', text);
            try {
                const data = JSON.parse(text);

                if (data.success) {
                    showToast('角色保存成功！', 'success');
                    updateUserRoleDisplay(currentEditUserId, data.roles);
                    roleEditModal.hide();
                } else {
                    showToast('角色保存失败：' + data.error, 'error');
                }
            } catch (jsonError) {
                console.error('JSON解析错误:', jsonError);
                showToast('服务器响应格式错误', 'error');
            }
        })
        .catch(error => {
            console.error('保存角色失败:', error);
            showToast('网络错误：' + error.message, 'error');
        })
        .finally(() => {
            // 恢复保存按钮
            saveBtn.disabled = false;
            saveBtn.innerHTML = originalText;
        });
    }

    // 执行自动同步
    function performAutoSync() {
        if (!confirm('确定要执行普通账号自动同步吗？\n\n此操作将根据员工在职状态自动添加或移除普通账号角色。\n管理员角色不会受到影响。')) {
            return;
        }

        fetch('ajax_auto_sync.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            }
        })
        .then(response => {
            console.log('Auto sync response status:', response.status);
            if (!response.ok) {
                throw new Error(`HTTP错误: ${response.status}`);
            }
            return response.text();
        })
        .then(text => {
            console.log('Auto sync response text:', text);
            try {
                const data = JSON.parse(text);

                if (data.success) {
                    showToast(`✅ 自动同步成功！处理了 ${data.count} 条记录`, 'success');
                    setTimeout(() => {
                        location.reload(); // 刷新页面显示最新状态
                    }, 1500);
                } else {
                    showToast('❌ 自动同步失败：' + data.error, 'error');
                }
            } catch (jsonError) {
                console.error('JSON解析错误:', jsonError);
                showToast('服务器响应格式错误', 'error');
            }
        })
        .catch(error => {
            console.error('自动同步失败:', error);
            showToast('❌ 网络错误：' + error.message, 'error');
        });
    }

    // 更新用户角色显示
    function updateUserRoleDisplay(userId, roles) {
        const roleBadgesContainer = document.getElementById(`role-badges-${userId}`);
        if (!roleBadgesContainer) return;

        // 清空现有角色显示
        roleBadgesContainer.innerHTML = '';

        if (roles.length === 0) {
            roleBadgesContainer.innerHTML = '<span class="badge bg-light text-dark role-badge">无角色</span>';
        } else {
            roles.forEach(role => {
                let badgeClass = 'bg-secondary';
                if (role === '系统管理员') badgeClass = 'bg-danger';
                else if (role === '考试项目管理员') badgeClass = 'bg-primary';
                else if (role === '人事管理员') badgeClass = 'bg-warning';
                else if (role === '普通账号') badgeClass = 'bg-secondary';

                const badge = document.createElement('span');
                badge.className = `badge ${badgeClass} role-badge`;
                badge.textContent = role;
                roleBadgesContainer.appendChild(badge);
            });
        }

        console.log('✅ 用户角色显示已更新:', userId, roles);
    }

    // 显示Toast消息
    function showToast(message, type = 'info') {
        const toastContainer = document.querySelector('.toast-container');

        let bgClass = 'bg-info';
        let icon = 'fas fa-info-circle';

        if (type === 'success') {
            bgClass = 'bg-success';
            icon = 'fas fa-check-circle';
        } else if (type === 'error') {
            bgClass = 'bg-danger';
            icon = 'fas fa-exclamation-triangle';
        } else if (type === 'warning') {
            bgClass = 'bg-warning';
            icon = 'fas fa-exclamation-circle';
        }

        const toastId = 'toast-' + Date.now();
        const toastHtml = `
            <div class="toast ${bgClass} text-white" id="${toastId}" role="alert" aria-live="assertive" aria-atomic="true" data-bs-delay="4000">
                <div class="toast-body">
                    <i class="${icon}"></i> ${message}
                    <button type="button" class="btn-close btn-close-white float-end" data-bs-dismiss="toast" aria-label="Close"></button>
                </div>
            </div>
        `;

        toastContainer.insertAdjacentHTML('beforeend', toastHtml);

        const toastElement = document.getElementById(toastId);
        const toast = new bootstrap.Toast(toastElement);
        toast.show();

        // 自动移除Toast元素
        toastElement.addEventListener('hidden.bs.toast', function() {
            toastElement.remove();
        });
    }

    // 切换调试信息显示
    function toggleDebug() {
        const debugContent = document.getElementById('debugContent');
        if (debugContent.style.display === 'none') {
            debugContent.style.display = 'block';
        } else {
            debugContent.style.display = 'none';
        }
    }
    </script>

    <?php
    // 关闭数据库连接
    if (isset($conn) && $conn instanceof mysqli) {
        $conn->close();
    }
    ?>
</body>
</html>